package com.fangcang.ebk.common.controller;

import com.fangcang.ebk.common.constant.CommonConstant;
import com.fangcang.ebk.common.dto.EbkUserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

public class BaseController implements Serializable {
    private static final long serialVersionUID = 7680335961152813170L;

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 获取已登录用户的会员Id
     */
    public EbkUserDTO getCacheUser(){
        if (getSession()==null || getSession().getAttribute(CommonConstant.SESSION_SYSUSER)==null){
            return null;
        }
        return (EbkUserDTO) getSession().getAttribute(CommonConstant.SESSION_SYSUSER);
    }

    /**
     * 获取当前访问者的微信openid
     * @return
     */
    public String getCacheVisitWxOpenId(){
        return getSession()==null?null:(String)getSession().getAttribute(CommonConstant.SESSION_VISIT_WX_OPENID);
    }

    /**
     * 获取微信自动登录访问源URL（微信自动登录跳转用）
     */
    public String getWxSrcVisitUrl(){
        return (String)getSession().getAttribute(CommonConstant.SESSION_WX_SRC_VISIT_URL);
    }

    /**
     * 设置微信自动登录访问源URL（微信自动登录跳转用）
     */
    public void setWxSrcVisitUrl(String wxSrcVisitUrl){
        if(StringUtils.isBlank(wxSrcVisitUrl)){
            getSession().removeAttribute(CommonConstant.SESSION_WX_SRC_VISIT_URL);
        }else{
            getSession().setAttribute(CommonConstant.SESSION_WX_SRC_VISIT_URL, wxSrcVisitUrl);
        }
    }
}
